package com.example.bbsbe.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class FileService {

    @Value("./media/")
    private String mediaRoot;

    public Map<String, Object> saveImage(MultipartFile file, String username) {
        Map<String, Object> response = new HashMap<>();

        try {
            String fileName = username + "_" + System.currentTimeMillis() + "_" +
                    Objects.requireNonNull(file.getOriginalFilename());
            Path path = Paths.get(mediaRoot, fileName);
            Files.createDirectories(path.getParent());
            Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);

            response.put("file", fileName);
            response.put("code", 0);
            response.put("msg", "图片上传成功！");
        } catch (IOException e) {
            response.put("file", "");
            response.put("code", 1);
            response.put("msg", "图片上传失败！");
        }
        return response;
    }

    public Map<String, Object> saveEditorImage(MultipartFile file, String username) {
        Map<String, Object> response = new HashMap<>();

        try {
            String fileName = username + "_" + System.currentTimeMillis() + "_" +
                    Objects.requireNonNull(file.getOriginalFilename());
            Path path = Paths.get(mediaRoot, fileName);
            Files.createDirectories(path.getParent());
            Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);

            Map<String, Object> data = new HashMap<>();
            data.put("url", "https://www.yushi.chat/media/" + fileName);

            response.put("errno", 0);
            response.put("data", data);
        } catch (IOException e) {
            response.put("errno", 1);
            response.put("message", "失败");
        }
        return response;
    }

    public Map<String, Object> saveEditorVideo(MultipartFile file, String username) {
        return saveEditorImage(file, username); // 实现方式相同
    }
}
